//
//  MerchantsViewController.m
//  PalmChangtu
//
//  Created by osoons on 15/6/17.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//
#import "MerchantBaseInfoViewController.h"
#import "RelesedGoodsViewController.h"
#import "ConnectViewController.h"
#import "AboutProtocoliViewController.h"
#import "ReleseGoodsViewController.h"
#import "MerchantsViewController.h"
#import "MeranchRegisterViewController.h"
#import "LoginViewController.h"
#import "MainTabbarController.h"
#import "ContactUSViewController.h"
#import "ShareUserModel.h"
#import "BaseUrlConfig.h"
#import "AFNetworking.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "GTMDefines.h"
#import "GTMBase64.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "NotLoggedInViewController.h"
#import "UserRegisterViewController.h"

@interface MerchantsViewController ()

@end

@implementation MerchantsViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    
    if([ShareUserModel shareUserModel].user.storeType.integerValue!=0)
        {
        
        
        self.btnAplayRegister.hidden = YES;
        self.btnLoginAction.hidden = YES;
        self.Viewline.hidden = YES;
        
        }
    else
        {
        self.btnAplayRegister.hidden = NO;
        self.btnLoginAction.hidden = NO;
        self.Viewline.hidden = NO;

        }

}
-(void)viewDidAppear:(BOOL)animated
{
    
    
    
    ShareUserModel * userUpdate = [ShareUserModel shareUserModel];
    
    
    
    self.labNameText.text=  [NSString stringWithFormat:@"欢迎%@登录!您的商户有效期限至2017年12月",userUpdate.user.userName];
    
    if (userUpdate.user.photoUrl.length!=0) {
            //        NSData * data = [[NSData alloc] initWithBase64EncodedString:[ShareUserModel shareUserModel].user.photoUrl options:NSDataBase64DecodingIgnoreUnknownCharacters];
            //
            //
            //        UIImage *_decodedImage = [UIImage imageWithData:data];
        
        
        
        
        NSLog(@"%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",hostUserImage,userUpdate.user.photoUrl]]);
        
        
        [self.imageHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",hostUserImage,userUpdate.user.photoUrl]] placeholderImage:[UIImage imageNamed:@"我的默认头像"]];
    }
    else
        {
        [self.imageHead setImage:[UIImage imageNamed:@"我的默认头像"]];
        
        
        }



}
- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    [_v_Top.lalTitel setText:@"掌中昌图"];
    
    [_v_Top.btnGoback setHidden:YES];
    _v_Top.parentController = self.navigationController;
    
    
    [_btnAplayRegister removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnAplayRegister addTarget:self action:@selector(btnRegisterAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnLoginAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnLoginAction addTarget:self action:@selector(btnLoginAction:) forControlEvents:UIControlEventTouchUpInside];

    [self addCustomGestures];
    // Do any additional setup after loading the view from its nib.
}

- (void)btnLoginAction:(UIButton *)btnLogin
{
//    LoginViewController * comment =[[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
//    
//    [self presentViewController:comment animated:YES completion:^{
//        
//    }];
//    
    NotLoggedInViewController *  NotLoggedInView  =[[NotLoggedInViewController alloc] initWithNibName:@"NotLoggedInViewController" bundle:nil];
    NotLoggedInView.string = @"2";
    
    [self presentViewController: NotLoggedInView animated:NO completion:NULL];
    //    LoginViewController * Loginview = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
//    Loginview.string =  @"2";
//    [self presentViewController:Loginview animated:YES completion:^{
//        
//    }];

    
}

- (void)btnRegisterAction:(UIButton *)btnRegister
{
    
    UserRegisterViewController * RegisterView =[[UserRegisterViewController alloc] initWithNibName:@"UserRegisterViewController" bundle:nil];

    RegisterView.string = @"2";
    [self presentViewController:RegisterView animated:YES completion:0];

    
}




#pragma mark - 添加自定义的手势（若不自定义手势，不需要下面的代码）

- (void)addCustomGestures {
    /*
     *注意：
     *添加自定义手势时，必须设置UIGestureRecognizer的属性cancelsTouchesInView 和 delaysTouchesEnded 为NO,
     *否则影响地图内部的手势处理
     */
    UITapGestureRecognizer *singleTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlesingleViewBaseInfoTouchTap:)];
    singleTouch.delegate = self;
    singleTouch.numberOfTapsRequired = 1;
    singleTouch.cancelsTouchesInView = NO;
    singleTouch.delaysTouchesEnded = NO;
    
    [self.viewBaseInfo addGestureRecognizer:singleTouch];
    
    /*
     *注意：
     *添加自定义手势时，必须设置UIGestureRecognizer的属性cancelsTouchesInView 和 delaysTouchesEnded 为NO,
     *否则影响地图内部的手势处理
     */
    UITapGestureRecognizer *singleTouchScale = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleviewReleseGoodsTouchScaleTap:)];
    singleTouchScale.delegate = self;
    singleTouchScale.cancelsTouchesInView = NO;
    singleTouchScale.delaysTouchesEnded = NO;
    [singleTouchScale requireGestureRecognizerToFail:singleTouch];
    [self.viewReleseGoods addGestureRecognizer:singleTouchScale];
    
    
    UITapGestureRecognizer *singleTouchGoods = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlesingleviewRelesedGoossTouchGoodsTap:)];
    singleTouchGoods.delegate = self;
    singleTouchGoods.cancelsTouchesInView = NO;
    singleTouchGoods.delaysTouchesEnded = NO;
    [singleTouchGoods requireGestureRecognizerToFail:singleTouchScale];
    [self.viewRelesedGooss addGestureRecognizer:singleTouchGoods];
    
    
    UITapGestureRecognizer *singleviewConnect = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlesingleviewConnectViewTouchGoodsTap:)];
    singleviewConnect.delegate = self;
    singleviewConnect.cancelsTouchesInView = NO;
    singleviewConnect.delaysTouchesEnded = NO;
//    [singleviewConnect requireGestureRecognizerToFail:singleviewConnect];
    [self.viewConnect addGestureRecognizer:singleviewConnect];

    
    UITapGestureRecognizer *singleviewAboutAgreement = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlesingleviewAboutAgreementTouchGoodsTap:)];
    singleviewAboutAgreement.delegate = self;
    singleviewAboutAgreement.cancelsTouchesInView = NO;
    singleviewAboutAgreement.delaysTouchesEnded = NO;
//    [singleviewAboutAgreement requireGestureRecognizerToFail:singleTouchScale];
    
    [self.viewAboutAgreement addGestureRecognizer:singleviewAboutAgreement];


    UITapGestureRecognizer *imageHeadSingleview = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageHeadSingleviewTouchGoodsTap:)];
    imageHeadSingleview.delegate = self;
    imageHeadSingleview.cancelsTouchesInView = NO;
    imageHeadSingleview.delaysTouchesEnded = NO;
    //    [singleviewAboutAgreement requireGestureRecognizerToFail:singleTouchScale];

    [self.imageHead  addGestureRecognizer:imageHeadSingleview];
    
}



#pragma mark -  上传头像

- (void)imageHeadSingleviewTouchGoodsTap:(UITapGestureRecognizer *)imageHeadSingleview
{

    UIAlertController * alter  = [[UIAlertController alloc] init] ;


    UIAlertAction * alterTakeOpen = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {
        [self pickImageFromAlbum];
    }];
    UIAlertAction * alterShoot = [UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {
        [self takePhotoOpen];

    }];


    UIAlertAction * alterCancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {

        
    }];
    

    [alter addAction:alterTakeOpen];

    [alter addAction:alterShoot];

    [alter addAction:alterCancle];

    [self presentViewController:alter animated:YES completion:^{

    }];




}


#pragma mark -  基本信息

- (void)handlesingleViewBaseInfoTouchTap:(UITapGestureRecognizer *)handlesingleViewBaseInfo{
    
    
    ShareUserModel * userShare = [ShareUserModel shareUserModel];
    if (userShare.user.storeType.integerValue != 0)
        {
        

        MerchantBaseInfoViewController * MoreDescribe =[[MerchantBaseInfoViewController alloc] initWithNibName:@"MerchantBaseInfoViewController" bundle:nil];
        
        [self.navigationController pushViewController:MoreDescribe animated:YES];
    }
    else
        {
        
        [[MainTabbarController ShareTabBarController] showMessage:@"你还没有申请成为商家，所以没有商家基本信息"];

        
        
        }
   
    
    
    NSLog(@"my handlesingleTouchTap");
}
    //更多商品描述
- (void)handlesingleviewRelesedGoossTouchGoodsTap:(UITapGestureRecognizer *)handlesingleRelesdGoodsTouchTap {
    
    
    
    
  
    ShareUserModel * userShare = [ShareUserModel shareUserModel];
    if (userShare.user.storeType.integerValue != 0)
        {
        
        
        RelesedGoodsViewController * RelesedGoodsView =[[RelesedGoodsViewController alloc] initWithNibName:@"RelesedGoodsViewController" bundle:nil];
        
        
        [self.navigationController pushViewController:RelesedGoodsView animated:YES];        }
    else
        {
        
        [[MainTabbarController ShareTabBarController] showMessage:@"你还没有申请成为商家，所以没有商家发布基本信息"];
        
        
        
        }
    
    
    NSLog(@"my handlesingleTouchTap");
}

    //已发布

- (void)handleSingleviewReleseGoodsTouchScaleTap:(UITapGestureRecognizer *)handleSingleTouchScaleTap {
    /*
     *do something
     */
    
    
    ShareUserModel * userShare = [ShareUserModel shareUserModel];
    if (userShare.user.storeType.integerValue != 0)
        {
        
        
        ReleseGoodsViewController * RelesedGoodsView =[[ReleseGoodsViewController alloc] initWithNibName:@"ReleseGoodsViewController" bundle:nil];
        
        [self.navigationController pushViewController:RelesedGoodsView animated:YES];
        
     }
    else
        {
        
        [[MainTabbarController ShareTabBarController] showMessage:@"你还没有申请成为商家，所以没有商家已发布基本信息"];
        
        
        
        }

    
    NSLog(@"my handleSingleTouchScaleTap");
}

- (void)handlesingleviewAboutAgreementTouchGoodsTap:(UITapGestureRecognizer *)handlesingleTouchGoodsTap {
    /*
     *do something
     */
    NSLog(@"my handlesingleTouchGoodsTap");
    
    AboutProtocoliViewController * AboutProtocoliView  =[[AboutProtocoliViewController alloc] initWithNibName:@"AboutProtocoliViewController" bundle:nil];
    [self.navigationController pushViewController:AboutProtocoliView animated:YES];
    
    
    
}
    //联系我们
- (void)handlesingleviewConnectViewTouchGoodsTap:(UITapGestureRecognizer *)handlesingleTouchGoodsTap {
    /*
     *do something
     */
    NSLog(@"my handlesingleTouchGoodsTap");

    ContactUSViewController * ConnectView =[[ContactUSViewController alloc] initWithNibName:@"ContactUSViewController" bundle:nil];
    [self.navigationController pushViewController:ConnectView animated:YES];
    

//    ConnectViewController * ConnectView =[[ConnectViewController alloc] initWithNibName:@"ConnectViewController" bundle:nil];
//    [self.navigationController pushViewController:ConnectView animated:YES];
//    
}




//打开摄像头
-(void)takePhotoOpen
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有摄像头
    if(![UIImagePickerController isSourceTypeAvailable:sourceType])
    {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }

    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;   // 设置委托
    imagePickerController.sourceType = sourceType;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];  //需要以模态的形式展示
}

#pragma mark 从用户相册获取活动图片
- (void)pickImageFromAlbum
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];

    imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];  //需要以模态的形式展示
}


//完成拍照
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];

    self.image = [info objectForKey:UIImagePickerControllerEditedImage];

    if (self.image == nil)
    {
        self.image = [info objectForKey:UIImagePickerControllerOriginalImage];

    }
    [self.imageHead setImage:self.image];


    UIAlertController * alter  = [[UIAlertController alloc] init] ;


    UIAlertAction * alterUpload = [UIAlertAction actionWithTitle:@"上传头像" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {


        NSData* pictureData = UIImageJPEGRepresentation(self.image,0.5);
        NSString *encodedImageStr = [pictureData base64Encoding];//图片转码成为base64Encoding，

        NSDictionary *dicParamJSON   = @{
                                         @"sessionId":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.sessionId],
                                         @"loginName":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.phone],
                                         @"img_str":encodedImageStr,
                                         @"userId":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.user_id]

                                         };

        [self ImageHeadRequest:dicParamJSON];
    }];




    UIAlertAction * alterCancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {
        [self.imageHead setImage:[UIImage imageNamed:@"我的默认头像"]];
    }];

    [alter addAction:alterUpload];
    [alter addAction:alterCancle];
    [self presentViewController:alter animated:YES completion:^{
        
    }];

}
//用户取消拍照
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{



    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - //请求数据  上传头像

-(void)ImageHeadRequest:(NSDictionary *)param
{

    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应


    NSString *   strUrl = [NSString stringWithFormat:@"%@%@",HostServer,analysis_imgAction];
    //    NSString *userShopID = [[NSUserDefaults standardUserDefaults]valueForKey:keyUser_id];

    [manager POST:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {


        NSLog(@"%@",responseObject);


        NSDictionary * dicRespon  = responseObject;
        [self ImageHeadRequestWith:dicRespon];

        [[LoadingView shareLoadingView] dismissAnimated:YES];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [[LoadingView shareLoadingView] dismissAnimated:YES];
        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }];
    
    
    
    
}

-(void)ImageHeadRequestWith:(NSDictionary *)dicRespon
{

    NSString * success = [dicRespon objectForKey:@"success"];

    if ( success.integerValue == 1)
    {

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


        ShareUserModel * userUpdate = [ShareUserModel shareUserModel];

        NSString * img_str = [dicRespon objectForKey:@"img_str"];

        [userUpdate.user setPhotoUrl:img_str];

        [self viewDidAppear:YES];

    }
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
